<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>使用Vuex实现加入购物车</title>
  <script src="../vue.js"></script>
  <script src="../vuex.min.js"></script>
  <style>
    #app{
      width:500px;
      height:250px;
      border: 2px solid #999;
      border-radius: 10px;
      margin:40px auto;
      padding: 0 20px;
      position: relative;
    }

    header{
      text-align: right;
      border-bottom: 2px solid #999;
    }
    
    ul,li{
      margin:0;
      padding:0;
    }
    
    li{
      line-height: 1.8;
      list-style-type: none;
    }

    .cart{
      width:180px;
      border: 2px dashed #999;
      position: absolute;
      padding:10px;
      top:70px;
      right:20px;
      background-color: #ddd;
    }
  </style>
</head>
<body>

<div id="app">
  <header><p>购物车中商品数量：{{cartCount}}</p></header>
  <div class="product-list">
    <product name="华为Mate40 Pro"></product>  
    <product name="iPhone 12 pro"></product>
    <product name="小米11 Ultra"></product>  
    <product name="vivo S9"></product>  
  </div>
  <cart></cart>
</div>
<script>
  const store = new Vuex.Store({
    state:{
      products:[]  
    },
    getters:{
        products(state){
          return state.products;
        }
    },
    mutations: {
      addToCart(state, name){
        if(!state.products.includes(name))
          state.products.push(name);
      },
      checkOut(state){
          //……这里省略下订单的逻辑……
          state.products=[];
      }
    }
  });

  const product = Vue.component("product", {
      props:['name'],
      methods: {
          addToCart(){
            this.$store.commit("addToCart", this.name);
          }
      },
      template:`
      <p :name="name">
        {{name}} 
        <button @click="addToCart">加入购物车</button>
      </p>`
  });

  const cart = Vue.component("cart", {
      methods: {
          checkOut(){
            this.$store.commit("checkOut");
          }
      },
      template:`
      <div class="cart">
        <ul>
          <li v-for="item in $store.getters.products">{{item}}</li>
        </ul>
        <button @click="checkOut">确定下单</button>
      </div>`
  });

  const vm = new Vue({
    el: '#app',
    store,
    computed: {
        cartCount(){
           return this.$store.getters.products.length;
        }
    }
  });

</script>
</body>
</html>